package com.itheima.dao;

import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 角色操作类
 */
public interface IRoleDao {

    /**
     * 根据用户id查询角色信息返回Role表信息
     * @param userid
     * @return
     */
    @Select("select * from role where id in (select ROLEID from USERINFO_ROLE where  USERID = #{userid})")
    public List<Role> findRoleByUserId(String userid);

    /**
     * 根据用户id查询角色信息返回Role表和相关联的资源表permissions信息(多对多)
     * @param userid
     * @return
     */
    @Select("select * from role where id in (select ROLEID from USERINFO_ROLE where  USERID = #{userid})")
    @Results({
            @Result(id = true,property ="id",column = "id",javaType = String.class),
            @Result(property ="roleName",column = "roleName",javaType = String.class),
            @Result(property ="roleDesc",column = "roleDesc",javaType = String.class),
            @Result(property ="permissions",column = "id",javaType = List.class,many = @Many(select = "com.itheima.dao.IPermissionDao.findPermissionByRoleId"))
    })
    public List<Role> findRoleWithPermissionsByUserId(String userid);

    /**
     * 查询所有角色
     * @return
     */
    @Select("select * from ROLE")
    public List<Role> findRoleAll();

    /**
     * 添加角色
     * @param role
     * @return
     */
    @Insert("insert into role(rolename,roledesc) values(#{roleName},#{roleDesc})")
    public int saveRole(Role role);


    /**
     * 查询此角色可以添加的权限
     * @param roleId
     * @return
     */
    @Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{roleId})")
    List<Permission> findAdditablePermission(String roleId);

    /**
     * 给角色添加权限
     * @param roleId
     * @param permissionId
     */
    @Insert("insert into role_permission values(#{permissionId},#{roleid})")
    void addPermission(@Param("roleid") String roleId,@Param("permissionId") String permissionId);

    /**
     * 根据id查询角色信息
     * @param roleId
     * @return
     */
    @Select("select * from role where id = #{roleId}")
    @Results({
            @Result(id = true,property ="id",column = "id",javaType = String.class),
            @Result(property ="roleName",column = "roleName",javaType = String.class),
            @Result(property ="roleDesc",column = "roleDesc",javaType = String.class),
            @Result(property ="permissions",column = "id",javaType = List.class,many = @Many(select = "com.itheima.dao.IPermissionDao.findPermissionByRoleId"))
    })
    Role findById(String roleId);
}
